package user.com.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import user.com.entity.Dto.UserLoginDto;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

@Aspect
@Component
public class FormatUrl {

    @Value("${file.path}")
    private String filePath;

    @Pointcut ( "@annotation(user.com.aspect.FormatFileURL)")
    public void formatFileURLs(){}

    @AfterReturning(value = "formatFileURLs()", returning = "result")
    public Object after(JoinPoint joinPoint , Object result){
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();

        FormatFileURL annotation = signature.getMethod().getAnnotation(FormatFileURL.class);

        if(annotation == null){
            return result;
        }

        String[] value = annotation.value();

        if(result instanceof Map){
            for(String str: value){
                if(((Map) result).get(str) != null){
                    ((Map) result).put(str,((Map) result).get(str).toString().substring(filePath.length()));
                }
            }
        }

        if(result instanceof List){
            for(String str: value){
                ((List)result).forEach(item ->
                        {
                            if(item instanceof Map){
                                if(((Map) item).get(str) != null){
                                    ((Map) item).put(str,((Map) item).get(str).toString().substring(filePath.length()));
                                }
                            }

                        }
                );
            }
        }

        if(result instanceof UserLoginDto){

            for(String str: value){
                try {
                    Field declaredField = UserLoginDto.class.getDeclaredField(str);

                    declaredField.setAccessible(true);

                    if(declaredField.get(result) == null){
                        continue;
                    }
                    declaredField.set(result,declaredField.get(result).toString().substring(filePath.length()));
                } catch (NoSuchFieldException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }
}
